import React from 'react';
import { inject, observer } from 'mobx-react';
import { Browser, BrowserHrm, Upload } from 'weaver-mobile-page'
import { withRouter } from 'react-router-dom';
import { Tools, InputItem, WhiteSpace, Select, TextareaItem, DatePicker, List, Button, FilePicker, WingBlank, Icon, Toast, Modal, Bubble, Accordion } from 'weaver-mobile';
import { createForm } from 'rc-form';
import querystring from "querystring";
import { toJS } from 'mobx';
import * as Util from "../../util";
import * as GoalAddAPI from '../../api/goal/goalAdd'
const getLabel = Tools.getLabel;
const { FormItem } = List;
const { DatePickerInput } = DatePicker;

@inject('goalAddStore', 'goalMainStore', 'goalCommonStore')
@withRouter
@observer
class GoalAdd extends React.Component {
    constructor(props) {

        super(props);
        this.store = this.props.goalAddStore;
        this.state = {
            periodData: [
                { key: "0", selected: false, showname: "" },
                { key: "1", selected: false, showname: getLabel(19398, '月度') },
                { key: "2", selected: false, showname: getLabel(17495, '季度') },
                { key: "3", selected: true, showname: getLabel(17138, '年度') },
                { key: "4", selected: false, showname: getLabel(390757, '三年') },
                { key: "5", selected: false, showname: getLabel(390758, '五年') },
            ],
            files: [],

        }

    }

    componentWillMount() {
        this.store.getAllCates();
        this.initData();
    }

    componentDidMount() {


    }

    /**
     * 初始化默认时间
     */
    initData = () => {
        let { principaler, nowyear, nowseason } = this.props.goalMainStore;
        let { setValue, clearData, onInputChange, onChangeBrowser, params, setParamsValue, computeEndDate, setSupGoalBrowserValue, changeCategory, changeMaxUploadSize } = this.props.goalAddStore;
        let search = this.props.location.search.replace('?', '');
        let parse = querystring.parse(search);
        let { type, period, parentid, parentName } = parse;
        clearData();  //重置值
        if (type) {
            onChangeBrowser(type, "cate");
        }
        if (period) {
            period == "2" ? computeEndDate(period, nowseason, nowyear) : period == "3" ? computeEndDate(period, "", nowyear) : computeEndDate(period)
        } else {
            computeEndDate("3", "", nowyear)
        }
        setValue(toJS(principaler), "principal");
        if (parentid && parentName) {
            setSupGoalBrowserValue(parentid, parentName)
            onChangeBrowser([{ id: parentid, name: parentName }], "parentid")
        }
        Tools.callApi({
            url: "/api/workrelate/goal/fileCategory",
            method: "GET",
            params: {},
            type: "json"
        }).then((data) => {
            if (data.status == 1) {
                changeCategory(data.secId)
                changeMaxUploadSize(data.maxsize)
            }
        })
    }

    /**
     * 新建目标
     */
    addGoal = () => {
        let { params, setLoading } = this.props.goalAddStore;
        let search = this.props.location.search.replace('?', '');
        let parse = querystring.parse(search);
        params = this.handleParams(params);
        params = this.setOrgData(params);

        if (this.checkValue(params)) {
            setLoading(true);
            GoalAddAPI.addGoal(params).then(res => {
                if (res.status) {
                    if (res.code == 0) {
                        Bubble.success(getLabel(22619, '保存成功'), 1, {}, 1, () => {
                            if (parse.parentid && parse.parentid != "") {
                                this.props.history.go(-1)
                            } else {
                                this.props.history.replace("/goalHome/goalDetail?id=" + res.goalId)
                            }
                        })
                    } else if(res.code == 1) {
                        Bubble.error(getLabel(508882, '保存出错,您没有给已选上级目标新建下级目标的权限'), 1, {}, 1, () => {
                            this.props.history.go(-1)
                        })
                    }else {
                        Bubble.error(getLabel(521871, '责任人没有创建该组织目标的权限'), 1, {}, 1)
                    }
                } else {
                    Bubble.error(getLabel(508744, '保存出错,请重新尝试或联系管理员'), 1, {}, 1, () => {
                        this.props.history.go(-1)
                    })
                }
                setLoading(false);
            })
        }

    }

    setOrgData = (params) =>{
        const {goalMainStore:{condtype,typeId,orgId}} = this.props;
        params.condtype = condtype;
        params.typeId = typeId;
        params.orgId = orgId;
        return params;
    }

    checkValue = (params) => {
        if (params.goalName == "") {
            Bubble.warning(getLabel('508796', '目标名称不能为空'), 1); // 错误提示
            return false;
        }
        return true;
    }

    /**
     * 处理params的数组
     */
    handleParams = (params) => {
        for (let key in params) {
            if (key == 'principalid' || key == 'parentid' || key == 'partnerid' || key == 'taskids' ||
                key == 'docids' || key == 'wfids' || key == 'crmids' || key == 'projectids' || key == 'goalids') {
                let str = '', arr = [];
                params[key].forEach((element) => {
                    arr.push(element.id)
                })
                params = { ...params, [key]: arr.toString() }
            }
        }
        return params;
    }

    /**
     * 责任人判断
     */
    onBrowser = (v) => {
        const { onChangeBrowser, setState } = this.props.goalAddStore;
        if (toJS(v).length == 0) {
            Bubble.warning(getLabel('508801', '责任人不能为空'), 1)
            return;
        } else {
            onChangeBrowser(v, "principalid")
            setState({ principalHrmBrowserValue: v });
        }
    }


    render() {
        const { goalCommonStore, goalAddStore, goalMainStore } = this.props;
        const { cateList, onInputChange, onChangeBrowser, params, onFileChange, supGoalBrowser, supGoalBrowserValue, principalHrmBrowser, principalHrmBrowserValue, partHrmBrowser, partHrmBrowserValue, realteGoalBrowser, realteGoalBrowserValue,
            realteTaskBrowser, realteTaskBrowserValue, realteDocBrowser, realteDocBrowserValue, realteWorkFlowBrowser, realteWorkFlowBrowserValue, realteCustomerBrowser, realteCustomerBrowserValue,
            realteProBrowser, realteProBrowserValue, relateUploadValue, setState, uploadStore, changeArray, category, maxUploadSize, loading } = goalAddStore;
        const { condtype } = goalMainStore;
        let { periodData, files } = this.state;
        if (loading) {
            goalCommonStore.showLoading()
        } else {
            goalCommonStore.closeLoading()
        }
        return (
            <div className="main-content-wrapper">
                <div className="workrelate_mobile_add_goal workrelate-condition workrelate-upload workrelate-goal-task-condition">
                    <Accordion defaultActiveKey="0">
                        <Accordion.Panel header={getLabel('81711', '基本信息')} className="custom-header">
                            <List>
                                <FormItem
                                    required={params.goalName ? false : true}
                                    extra={<Icon size='xxs' type="editor" />}
                                    label={getLabel('33439', '名称')}
                                    line
                                    noBorder
                                    content={
                                        <InputItem
                                            placeholder={getLabel(83869, '请输入')}
                                            value={params.goalName}
                                            autoHeight
                                            onChange={(v) => onInputChange(v, "goalName")}
                                        />
                                    }
                                />
                            </List>
                            <List>
                                <Browser
                                    label={getLabel(19709, '上级目标')}
                                    store={supGoalBrowser}
                                    hasAdvanceSerach
                                    type="wrlgoal"
                                    dataParams={{ parentid:'',condtype }}
                                    // dataURL="/spa/workrelate/static/index.html?#/main/workrelate/goal/goalDetail?id="
                                    valueArray={supGoalBrowserValue}
                                    noBorder
                                    onChange={(...arg) => {
                                        onChangeBrowser(arg[2], "parentid")
                                        setState({ supGoalBrowserValue: arg[2] });
                                    }}
                                />
                            </List>
                            <List>
                                <List.FormItem
                                    noBorder
                                    content={
                                        <Select
                                            options={cateList}
                                            label={getLabel(500401, '类型')}
                                            value={params.cate}
                                            onChange={(value, showname) => onInputChange(value, "cate")}
                                        />}
                                />
                            </List>
                            <List>
                                <FormItem
                                    extra={<Icon size='xxs' type="editor" />}
                                    label={getLabel(433, '描述')}
                                    line
                                    noBorder
                                    content={
                                        <TextareaItem
                                            placeholder={getLabel(83869, '请输入')}
                                            autoHeight
                                            editable={true}
                                            value={params.remark}
                                            onChange={value => onInputChange(value, "remark")}
                                        />
                                    }
                                />
                            </List>
                            <List>
                                <BrowserHrm
                                    label={getLabel(16936, '责任人')}
                                    store={principalHrmBrowser}
                                    hasAdvanceSerach
                                    isSingle={true}
                                    type={1}
                                    viewAttr={3}
                                    valueArray={principalHrmBrowserValue}
                                    onChange={(...arg) => {
                                        this.onBrowser(arg[2])
                                    }}
                                />
                            </List>

                            <List>
                                <BrowserHrm
                                    label={getLabel(15761, '参与人')}
                                    store={partHrmBrowser}
                                    hasAdvanceSerach
                                    isSingle={false}
                                    type={1}
                                    valueArray={partHrmBrowserValue}
                                    onChange={(...arg) => {
                                        onChangeBrowser(arg[2], "partnerid")
                                        setState({ partHrmBrowserValue: arg[2] });
                                    }}
                                />
                            </List>
                            <List>
                                <List.FormItem
                                    noBorder
                                    content={
                                        <Select
                                            options={periodData}
                                            label={getLabel(15386, '周期')}
                                            viewAttr={2}
                                            value={params.period}
                                            onChange={(value, showname) => onInputChange(value, "period")}
                                        />}
                                />
                            </List>
                            <List>
                                <FormItem
                                    label={getLabel(741, '结束日期')}
                                    line
                                    content={(<DatePickerInput
                                        placeholder={getLabel(83869, '请输入')}
                                        mode={"date"}
                                        value={params.enddate}
                                        onChange={(value) => onInputChange(value, "enddate")}
                                    />)}
                                />
                            </List>
                        </Accordion.Panel>
                        <Accordion.Panel header={getLabel('22078', '相关信息')} className="custom-header">
                            <List>
                                <Browser
                                    label={getLabel(382586, '相关目标')}
                                    store={realteGoalBrowser}
                                    hasAdvanceSerach
                                    isSingle={false}
                                    type={"wrlgoal"}
                                    valueArray={realteGoalBrowserValue}
                                    onChange={(...arg) => {
                                        onChangeBrowser(arg[2], "goalids")
                                        setState({ realteGoalBrowserValue: arg[2] });
                                    }}
                                />
                            </List>
                            <List>
                                <Browser
                                    label={getLabel(33414, '相关任务')}
                                    store={realteTaskBrowser}
                                    hasAdvanceSerach
                                    isSingle={false}
                                    type="wrltsk"
                                    valueArray={realteTaskBrowserValue}
                                    onChange={(...arg) => {
                                        onChangeBrowser(arg[2], "taskids")
                                        setState({ realteTaskBrowserValue: arg[2] });
                                    }}
                                />
                            </List>
                            <List>
                                <Browser
                                    label={getLabel(857, '相关文档')}
                                    store={realteDocBrowser}
                                    hasAdvanceSerach
                                    isSingle={false}
                                    type={9}
                                    valueArray={realteDocBrowserValue}
                                    onChange={(...arg) => {
                                        onChangeBrowser(arg[2], "docids")
                                        setState({ realteDocBrowserValue: arg[2] });
                                    }}
                                />
                            </List>
                            <List>
                                <Browser
                                    label={getLabel(22105, '相关流程')}
                                    store={realteWorkFlowBrowser}
                                    hasAdvanceSerach
                                    isSingle={false}
                                    type={16}
                                    valueArray={realteWorkFlowBrowserValue}
                                    onChange={(...arg) => {
                                        onChangeBrowser(arg[2], "wfids")
                                        setState({ realteWorkFlowBrowserValue: arg[2] });
                                    }}
                                />
                            </List>
                            <List>
                                <Browser
                                    label={getLabel(783, '相关客户')}
                                    store={realteCustomerBrowser}
                                    hasAdvanceSerach
                                    isSingle={false}
                                    type={7}
                                    valueArray={realteCustomerBrowserValue}
                                    onChange={(...arg) => {
                                        onChangeBrowser(arg[2], "crmids")
                                        setState({ realteCustomerBrowserValue: arg[2] });
                                    }}
                                />
                            </List>
                            <List>
                                <Browser
                                    label={getLabel(782, '相关项目')}
                                    store={realteProBrowser}
                                    hasAdvanceSerach
                                    isSingle={false}
                                    type={8}
                                    valueArray={realteProBrowserValue}
                                    onChange={(...arg) => {
                                        onChangeBrowser(arg[2], "projectids")
                                        setState({ realteProBrowserValue: arg[2] });
                                    }}
                                />
                            </List>
                            <List className="formitem-upload">
                                <FormItem
                                    label={getLabel(22194, '相关附件')}
                                    line
                                    noBorder
                                    content={<Upload
                                        store={uploadStore}
                                        datas={relateUploadValue}
                                        uploadUrl={'/api/doc/upload/uploadFile2Doc?category=' + category}
                                        editable={true}
                                        onChange={onFileChange}
                                        maxUploadSize={maxUploadSize}
                                        showUploader={true}
                                        showUploadTime={true}
                                        onItemClick={(file, idx, files) => {
                                            window.openLink.openDocument(file.fileid);
                                        }}
                                        onFileLoad={(file) => {
                                            window.openLink.getWeaverFile("/weaver/weaver.file.FileDownload?fileid=" + file.imagefileid + "&download=1")
                                        }}
                                    />
                                    }
                                />
                            </List>
                            <WingBlank>

                            </WingBlank>
                        </Accordion.Panel>
                    </Accordion>

                </div>
                <div className="workrelate_mobile_goal_bottom">
                    <Button type="primary" onClick={this.addGoal}>{getLabel(86, '保存')}</Button>
                </div>
            </div>
        )
    }

}

export default GoalAdd;